package com.gel.aiagent.tools;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import okhttp3.HttpUrl;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/*联网搜索工具*/
public class WebSearchTool {
    private static final String SEARCH_API_URL="https://www.searchapi.io/api/v1/search";
    private final String apiKey;

    public WebSearchTool(String apiKey) {
        this.apiKey = apiKey;
    }

    @Tool(description = "Search  information from baidu Search Engine")
    public String searchWeb(@ToolParam(description = "Search query keyword") String query){
        Map<String ,Object> requestBody = new HashMap<>();
        requestBody.put("q",query);
        requestBody.put("api_key",apiKey);
        requestBody.put("engine" ,"baidu");
        try{
            String response = HttpUtil.get(SEARCH_API_URL, requestBody);
            JSONObject jsonObject = JSONUtil.parseObj(response);
            JSONArray organicResults = jsonObject.getJSONArray("organic_results");
            //返回前几个字段
            List<Object> objects = organicResults.subList(0, 4);
            //拼接搜索结果为字符串
            String result = objects.stream().map(item -> {
                JSONObject jsonObject1 = (JSONObject) item;
                return jsonObject1.toString();
            }).collect(Collectors.joining(","));
            return result;
        }catch (Exception e){
            return "Error searching Baidu"+e.getMessage();
        }

    }
}
